<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <PageTools>
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <template #right>
          <el-button type="primary" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="primary" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="danger" size="small" @click="showDialog=true">添加员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="List">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template v-slot="{row}">
              <img
                v-imageerr="defaultImg"
                :src="row.staffPhoto || defaultImg"
                alt=""
                class="img"
                @click="showEwm(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column :formatter="formatEmployment" label="聘用形式" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry | dateFormat('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" :disabled="!checkPermission('look')" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('del')" @click="delInfo(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!--新增员工弹出框组件  -->
    <Addemployee :show-dialog.sync="showDialog" />

    <!-- 分配角色的弹出框组件 -->
    <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />

    <!-- 二维码弹层 -->
    <el-dialog title="二维码" :visible.sync="showEwmDialog">
      <canvas ref="myCanvas" />
    </el-dialog>
  </div>
</template>

<script>
import AssignRole from './components/assign-role.vue'
import qrCode from 'qrcode'
import defaultImg from '@/assets/common/head.jpg'
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import employeeEnum from '@/api/constant/employees'
import Addemployee from './components/add-employee.vue'
export default {
  name: 'Employees',
  components: {
    Addemployee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      pageSize: 5,
      total: 0,
      List: [],
      showDialog: false,
      defaultImg, // 默认图片
      showEwmDialog: false, // 二维码,
      showRoleDialog: false, // 角色分配弹出框
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 检查员工的权限按钮
    checkPermission(type) {
      const points = this.$store.getters.roles.points
      if (points.includes(type)) {
        return true
      } else {
        return false
      }
    },
    // 获取员工列表
    async getEmployeeList() {
      const { data: { total, rows }} = await reqGetEmployeeList(this.page, this.pageSize)
      this.List = rows
      this.total = total
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    // cellvalue 单元格的值
    formatEmployment(row, column, cellvalue, index) {
      const { hireType } = employeeEnum

      const result = hireType.find(item => item.id === +cellvalue)

      return result ? result.value : '未知'
    },
    // 点击删除
    async delInfo(id) {
      const res = await this.$confirm('确定永久删除此数据吗', '提示').catch(err => err)

      if (res === 'cancel') return

      await reqDelEmployee(id)

      // 点击删除当只有最后一条数据时跳到上一页
      if (this.List.length === 1 && this.page > 1) {
        this.page--
      }

      // 成功提示
      this.$message.success('删除成功')

      // 刷新数据
      this.getEmployeeList()
    },
    // 员工批量导出
    async handleDownload() {
    // 表头
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 获取所有的员工列表
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // 最终的结构: [[]]

      const newArr = [] // 外层的大数据
      rows.forEach(item => {
        const arr = []
        headersArr.forEach(value => {
          const englishkey = headersRelations[value]
          if (englishkey === 'formOfEmployment') {
            const obj = employeeEnum.hireType.find(v => v.id === item[englishkey])
            const res = obj ? obj.value : '未知'
            arr.push(res)
          } else {
            arr.push(item[englishkey])
          }
        })
        newArr.push(arr)
      })
      // webpack资源加载
      import('@/vendor/Export2Excel').then(excel => {
      // excel实现导出
        excel.export_json_to_excel({
          header: headersArr, // 表头
          data: newArr,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },
    // 点击显示二维码
    showEwm(url) {
      if (!url) return
      this.showEwmDialog = true

      this.$nextTick(() => {
        qrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 分配角色
    assignRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}

</script>

<style lang="scss" scoped>
.img{
    width: 100px;
    height: 100px;
    border-radius: 50%;
}
</style>

